﻿using System;
using System.Web;
using Inscriptionem.ORM;
using Inscriptionem.Services;

namespace Inscriptionem.MVC.Logging
{
    public class ExceptionLoggerModule : IHttpModule
    {
        public void Dispose()
        {

        }

        public void Init(HttpApplication context)
        {
            // TODO check configuration, if logging disabled
            context.Error += new EventHandler(context_Error);
        }

        void context_Error(object sender, EventArgs e)
        {
            if (!InstallService.IsDBAvailableAndCorrect)
            {
                return;
            }

            HttpApplication application = (HttpApplication) sender;
            Exception exception = application.Server.GetLastError();

            if (exception != null)
            {
                try
                {
                    DB db = new DB();
                    db.LogExceptions.AddObject(new LogException() { URL = application.Request.Url.ToString(), Message = exception.Message, Trace = exception.StackTrace, CreatedDate = DateTime.Now });
                    db.SaveChanges();
                }
                catch (Exception)
                {
                }
            }
        }
    }
}